function getAvailableStocks() {
  const getMoneyUrl = "getAvailableStocks";
  fetch(getMoneyUrl)
  .then(response => {
    if (response.ok) return response.json();
    else throw new Error("request failed");
  })
  .then(res => {
    setupAutoComplete(res);
  })
  .catch(error => {
    // if it fails wait 0.2s and repeat
    setTimeout(getAvailableStocks, 200);
  });

}



// https://goodies.pixabay.com/javascript/auto-complete/demo.html
// this could instead be done with AJAX via the server
// but this moves the stress away from the server onto the browser
// which is good, since the server should focus on fast updates of the values
// with modern amounts of ram, around 10k small strings is not a problem. (around 4kb)

function setupAutoComplete(availableStocks) {
  new autoComplete({
      selector: document.getElementById("stockSearch"),
      minChars: 2,
      source: function(term, suggest){
          term = term.toLowerCase();
          var choices = availableStocks;
          var matches = [];
          for (i=0; i<choices.length; i++)
              if (~choices[i].toLowerCase().indexOf(term)) matches.push(choices[i]);
          suggest(matches);
      }
  });
}

getAvailableStocks();
